// capture.cpp : Defines the entry point for the console application.
//

#include <windows.h>
#include <mmsystem.h>
#include <vfw.h>
#include <stdio.h>
#include <conio.h>


#include "../Capture/CapLib.h"

#define	MAX_FRAME 500
DWORD	MAGIC_ACTL=('A')+('C'<<8)+('T'<<16)+('L'<<24);

DWORD			mStartTime=0,
				mEndTime,mtime;
FILE			*save=0;

//#define CW 720
#define CW 320
#define CH 240

int Interlaced = 0;

#ifdef _LOGRUS_
int _cdecl  ProcessCompressed(void* data,int size)
#else
int _cdecl  ProcessCompressed(void* data,int size, int nType)
#endif
{
	if(save)
	{
		fwrite(&size,sizeof(int),1,save);
		fwrite(data,size,1,save);

	}
	return size;
}


int MessageLoop()
{
	MSG msg;

	while(1) {
		capPVR_grab();
		if (FrameNum++>MAX_FRAME) return 0;
	}

	while(1) {
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			if (msg.message == WM_QUIT) return 0;
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		WaitMessage();

	}
	// should never be executed
	return 0;
}



int main(int argc, char* argv[])
{
	int n;
	CAPLIBCREATESTRUCT cs;

	printf("Sample video capture program for pvr codec\n");
	printf("(C) 1999-2001 Streambox Inc.\n");

	for (n=1;n<argc;n++) {
		if (strcmp(argv[n],"/s")==0) {
			LPSTR szFilename=argv[n+1];
			if (szFilename==0) {
				printf("/s -save compressed video requires output file name!\n");
				continue;
			}
			save=fopen(szFilename,"wb");
			if (save){
					printf("saving compressed data to file: %s\n",szFilename);
					continue;
			}
			printf("/s - ignored, cannot open output file: %s\n",szFilename);

		}
		if (strcmp(argv[n],"/q")==0) {
			char *s=argv[n+1];
			if (s[0]-'0'>=0 && s[0]-'0'<10) {
				QUALITY=atoi(s);
			}
			printf("Quality factor: %d\n",QUALITY);
		}
	}
 

//	if (capPVR_Init(CW,CH,30)==0) return 0;
	
	ZeroMemory(&cs, sizeof(CAPLIBCREATESTRUCT));
	cs.h = CH;
	cs.w = CW;
	cs.nFPS = 30;
	cs.pParent = 0;
	if(!capPVR_Create(&cs)) return 0;
	capPVR_SetCallback(ProcessCompressed);


	if (save) {
		int w=CW,h=CH;
		fwrite(&MAGIC_ACTL,sizeof(int),1,save);
		fwrite(&w,4,1,save);
		fwrite(&h,4,1,save);

		fwrite(&Interlaced,4,1,save);              // LOGRUS
	}


	if (mStartTime==0) mStartTime=timeGetTime();
	MessageLoop();
	mEndTime=timeGetTime();
	if (mEndTime<mStartTime) mtime=mStartTime-mEndTime;
	else mtime=mEndTime-mStartTime;
	printf("Total   frames: %3.2f Total time     : %3.2f\n",(float)FrameNum,(float)(mtime/1000.0));
	printf("Sec. per frame: %3.2f Frames per sec.: %3.2f\n",
					(float)(mtime/1000.0/FrameNum),(float)(FrameNum/(mtime/1000.0)));



	//-------- clean up
	if (save) fclose(save);



	return 0;
}
